package ibm.websphere.monitor.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ibm.websphere.monitor.bean.UserInfo;
import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * <pre>
 * 	登陆鉴权 拦截器
 * </pre>
 * @copyright www.timotai.net
 * @author 这家伙真懒
 * @date 2016-1-12
 * <pre></pre>
 **/

public class LoginInterceptor extends AbstractInterceptor {

    @Override
    public void init() {
        // TODO Auto-generated method stub
        logger.info("【拦截器】【拦截器已被加载】");
    }


    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        logger.info("【拦截器】【拦截器已被销毁】");
    }


    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /**调试日志**/
    private Logger logger = Logger.getLogger(LoginInterceptor.class);

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {


        ActionContext actionContext =invocation.getInvocationContext();

        //获取REQUEST对象
        HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
        //设置header，防止网页缓存
        HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.addHeader("pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        Map<String, Object> session = actionContext.getSession();

        UserInfo userInfo = (UserInfo) session.get(Constants.SESSION_USER);

        //获取到namespace，还能够获取到要执行的方法，class等
        String namespace = invocation.getProxy().getNamespace();

        if ((namespace != null) && (namespace.trim().length() > 0)) {
            if ("/".equals(namespace.trim())) {
                // 说明是根路径，不需要再增加反斜杠了。
            } else {
                namespace += "/";
            }
        }

        String URL = namespace + invocation.getProxy().getActionName();
        if(URL.indexOf("Index")>0){
            return invocation.invoke();
        }else{
            //如果对象为空，则跳转到登陆页面
            if (userInfo != null) {
                try {
                    return invocation.invoke();
                }
                catch (Exception ex) {
                    ex.printStackTrace();
                    logger.error("调用action失败 url:"+URL,ex);
                    String errorMessage = ex+"<br/>"+ex.getMessage();
                    Throwable throwable = ex.getCause();
                    while(throwable!=null){
                        errorMessage += throwable.getMessage() +  "<br/>";
                        throwable = throwable.getCause();
                    }
                    request.setAttribute("errorMessage", errorMessage);
                    return Constants.ERROR;
                }
            }else{
                request.setAttribute("loginError", "没有登录或者登录超时。");
                logger.info("【登陆鉴权】【来访URL："+URL+"】【用户没有登陆】【"+request.getRemoteAddr()+"】");

                //设置要跳转的路径
                session.put(Constants.WAS_LOGIN_ERROR, request.getContextPath());
                request.setAttribute(Constants.WAS_RETURN_URL, request.getContextPath());
                return Constants.WAS_LOGIN;
            }
        }
    }

}
